<template>
  <view class="viewport">
    <view class="top_container" ref="headerRef">
      <view class="search_container">
        <input class="search_input" inputmode="search" confirm-type="search" placeholder="点击搜索主题" v-model="searchParam"
          @confirm="search" />
      </view>
      <view class="screen_container">
        <DaDropdown ref="daDropdownRef" v-model:dropdownMenu="dropdownMenuList" themeColor="#54B9CC" textColor="#394259"
          itemJustifyContent="flex-end" @confirm="handleConfirm" @close="handleClose" @open="handleOpen">
        </DaDropdown>
      </view>
    </view>



    <!-- <scroll-view scroll-y class="scroll-view" show-scrollbar="false"> -->
    <view class="item-container" :style="{marginTop:`${contentPaddingTop }px`}">
      <view class="nodata" v-if="datalist.length==0 &&!isLoading">
        <image class="no_data_img" src="../../static/images/blank.png"></image>
        <text class="no_data_text">暂无数据</text>
      </view>
      <view v-else v-for="(item,index) in datalist" class="case-item" @click="itemClick(item)">
        <view class="image_container">
          <image class="image_good" :src="`${baseURL}${item.dataPic}`">
          </image>
          <view class="tag">HUIDA 惠达</view>
        </view>
        <view class="item-right">
          <view class="right-container_title">
            <view class="good_name">{{item.goodsName}}</view>
          </view>
          <view class="right-container">
            <view class="right-title">分类</view>
            <view class="right-content">{{item.classtreeName}}</view>
          </view>
          <view class="right-container">
            <view class="right-title">品牌</view>
            <view class="right-content">{{item.brandName}}</view>
          </view>
          <view class="right-container">
            <view class="right-title">规格</view>
            <view class="right-content">{{item.skuName|| '100*100'}}</view>
          </view>
          <view class="right-container">
            <view class="right-title">指导价</view>
            <view class="right-content">{{item.pricesetAsprice}}</view>
          </view>
        </view>

      </view>

    </view>
    <!-- </scroll-view> -->
  </view>

</template>

<script setup lang="ts">
  import { getProductList, findProducList, queryChannelPage } from '@/services/home'
  import { onLoad, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';

  import { ref, onMounted, onBeforeUnmount, nextTick, getCurrentInstance } from 'vue';
  import { getClasstree } from '@/services/file';
  import Func from '@/utils/func';
  import { baseURL } from '@/utils/http';
  import DaDropdown from '@/components/da-dropdown/index.vue'

  const screenList1 = ref<any>([])
  const screenList2 = ref<any>([])
  const screenList3 = ref<any>([])

  // 一级分类
  const firstClass = ref<any>([])
  // 二级分类
  const secondClass = ref<any>([])


  let total = -1;
  let page = 1
  let channelCodeStr = ''
  const rows = 10
  const channelCode = 'delearchannelcode'//渠道
  const searchType = 'match_phrase'
  const vendibilityFlag = true
  const childFlag = true
  const hjFlag = true
  const dataStateStr = '0,2,3,4'
  const goodsType = '00,40,03'
  const goodsOrigin = '0,8'
  const bizType = 'sku'
  const sortField = ''
  let goodsClassParentcode = ''
  const goodsName = ref('')
  const channelName = ref('')
  const searchParam = ref('')
  const isLoading = ref(true)

  const datalist = ref<any[]>([])//数据源


  const headerRef = ref()
  const contentPaddingTop = ref(0)
  const daDropdownRef = ref(null)
  const dropdownMenuList = ref([
    {
      title: '渠道筛选',
      type: 'cell',
      prop: 'channel',
      showAll: true,
      showIcon: true,
      // value: '2', // 默认内容2
      // options: [],
      field: {
        label: 'channelName',
        value: 'channelCode',
        suffix: '',
      },
      // syncDataFn: queryChannelPage,
      // syncDataKey: 'data.list',
    },
    {
      title: '分类筛选',
      type: 'picker',
      prop: 'classify',
      showAll: true,
      showIcon: true,
      field: {
        label: 'label',
        value: 'value',
        children: 'children',
      },

    },

  ])

  let firstClassCode = '';
  let secondClassCode = '';
  let thirdClassCode = '';


  onMounted(() => {
    console.log('onMounted')
    // 获取系统信息
    const systemInfo = uni.getSystemInfoSync()
    const instance = getCurrentInstance()
    // 创建节点查询
    const query = uni.createSelectorQuery().in(instance)
    console.log(query)
    query.select('.top_container').boundingClientRect((res : any) => {
      console.log(res)
      if (res) {
        // 头部高度 = 状态栏高度 + 头部内容高度
        // 如果是自定义导航栏，可能需要加上状态栏高度
        contentPaddingTop.value = res.height
        console.log(contentPaddingTop.value)
        // 或者更精确的计算（如果头部包含状态栏占位）
        // const statusBarHeight = systemInfo.statusBarHeight || 20
        // contentPaddingTop.value = res.height
      }
    }).exec()
  })


  onLoad(() => {

    getOptions()
    getData(true)
  })


  //下拉刷新
  onPullDownRefresh(() => {
    getOptions()
    getData(true)
  })
  //到底触发 上拉加载
  onReachBottom(() => {
    if (total != -1 && datalist.value.length >= total) {
      uni.showToast({
        title: '已加载完全部',
        icon: 'none',
      })
      return
    }
    getData(false)
  })
  //搜索
  const search = () => {
    getData(true);
  }


  //递归处理 分类项
  const transformTree = (data : any) => {
    return data.map((item : any) => {
      // 创建新对象并替换字段
      const newItem : any = {
        label: item.classtreeName,
        value: item.classtreeCode,
        // ...item // 保留其他可能存在的属性
      };

      // 递归处理子节点
      if (item.childList && item.childList.length > 0) {
        newItem.children = transformTree(item.childList);
      }

      return newItem;
    });
  }


  //筛选确认
  function handleConfirm(v : any, selectedValue : any) {
    console.log('handleConfirm ==>', selectedValue)
    if (selectedValue.classify) {
      firstClassCode = selectedValue.classify[0]
      secondClassCode = selectedValue.classify[1]
      thirdClassCode = selectedValue.classify[2]
    }
    channelCodeStr = selectedValue.channel || ''
    getData(true)

  }
  function handleClose(v : any, callbackMenuList : any) {
    console.log('handleClose ==>', v, callbackMenuList)
  }
  function handleOpen(v : any) {
    console.log('handleOpen ==>', v)
  }
  //同步获取 筛选项
  async function getOptions() : Promise<any> {
    // 添加加载效果
    uni.showLoading({
      title: ''
    })
    // 通过方法更新异步数据
    const firstClasstree = await getClasstree({ goodsClass: 'B2B' })
    let options = []
    if (Func.notEmpty(firstClasstree)) {
      options = transformTree(firstClasstree)
    }
    console.log(options)

    //商品分类
    daDropdownRef.value?.updateMenu('classify', options, 'options')
    //渠道
    const channelList = await queryChannelPage()
    daDropdownRef.value?.updateMenu('channel', channelList.list, 'options')
    uni.hideLoading()
  }
  /**
   * 获取数据集
   */
  const getData = (refresh : boolean) => {
    if (refresh) {
      page = 1
    } else {
      page++;
    }
    uni.showLoading({
      title: ''
    })
    isLoading.value = true

    goodsClassParentcode = thirdClassCode || secondClassCode || firstClassCode || '-1'
    //查询
    findProducList({
      page,
      rows,
      channelCode,
      searchType,
      goodsOrigin,
      goodsType,
      vendibilityFlag,
      childFlag,
      hjFlag,
      bizType,
      sortField,
      goodsClassParentcode,
      searchParam: searchParam.value,
      channelCodeStr
      // goodsCode: '1015294714134466617'
    }).then((res : any) => {
      isLoading.value = false
      uni.hideLoading()
      console.log(res)
      total = res.total
      if (refresh) {
        datalist.value = res.list
      } else {
        res.list.forEach((item : any) => {
          datalist.value.push(item)
        })
      }
    }).catch(e => {
      uni.hideLoading()
      isLoading.value = false
    })
  }

  /**
   *
   */
  const itemClick = (item : any) => {
    uni.navigateTo({
      url: `/pages/product/productDetail?data=${JSON.stringify(item)}`
    })
  }
</script>

<style lang="scss">
  .viewport {

    height: 100vh;
    display: flex;
    flex-direction: column;
    background-color: white;

  }

  .top_container {

    padding-top: 100rpx;
    width: 100vw;
    background-color: white;
    // border-image: linear-gradient(180deg, rgba(97, 215, 237, 1), rgba(84, 185, 204, 1)) 2 2;
    display: flex;
    flex-direction: column;
    position: fixed;
    z-index: 100;
  }



  .search_container {

    border-radius: 30rpx;
    border: 2rpx solid #61D7ED;
    flex-direction: column;
    flex-grow: 1;
    padding: 15rpx 18rpx;
    margin: 5rpx 20rpx;
  }

  .search_input {
    background-color: white;
    font-size: 28upx;
  }

  .screen_container {
    margin-top: 10rpx;
    padding-left: 10rpx;
    padding-right: 10rpx;
    width: 100vw;

    border-bottom: 10rpx solid #F9FAFB;

  }




  .selelct {
    width: 35vw;
    border-radius: 10rpx;
    text-align: center;
    background-color: white;
    margin-right: 15rpx;
  }



  .lines {
    width: 1px;
    background-color: gray;
  }




  .nodata {
    display: flex;
    height: 80vh;
    align-items: center;
    flex-direction: column;

  }

  .no_data_img {
    margin-top: 25vh;
    height: 84rpx;
    width: 100rpx;
  }

  .no_data_text {
    margin-top: 30rpx;
    color: darkgray;
  }

  .item-container {
    flex-grow: 1;
    background-color: #F9FAFB;
  }

  .item-right {
    display: flex;
    flex-direction: column;
    margin-left: 30rpx;

  }

  .right-container_title {
    display: flex;
    flex-direction: row;
    flex-grow: 1;
  }

  .right-container {
    display: flex;
    flex-direction: row;
  }

  .right-title {
    height: 40rpx;
    min-width: 100rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 26rpx;
    color: rgba(28, 37, 58, 0.65);
    line-height: 40rpx;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }

  .right-content {
    height: 40rpx;
    margin-left: 10rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 26rpx;
    color: rgba(28, 37, 58, 0.65);
    line-height: 40rpx;
    text-align: left;
    overflow: hidden;
    font-style: normal;
    text-transform: none;
  }


  .case-item {
    display: flex;
    margin-top: 10rpx;
    padding: 20rpx 10rpx;
    background: #FFFFFF;
    // box-shadow: 0rpx 0rpx 16rpx 0rpx rgba(209, 227, 230, 0.58);
    border-radius: 2rpx 2rpx 2rpx 2rpx;



    .image_container {
      position: relative;
      height: 240rpx;
      width: 240rpx;
      box-sizing: border-box;
      border-radius: 16rpx;
      border: 3rpx solid #00C1D1;
      overflow: hidden;
      /* 设置溢出隐藏 */

      .image_good {
        width: 100%;
        height: 320rpx;
      }

      .tag {
        text-align: center;
        line-height: 40rpx;
        height: 40rpx;
        width: 160rpx;
        left: 0;
        top: 0;
        color: white;
        font-size: 20rpx;
        position: absolute;
        border-top-left-radius: 16rpx;
        border-bottom-right-radius: 16rpx;
        background-color: #00C1D1;
      }

    }

    .text {
      text-align: left;
      margin-top: 40rpx;
      font-size: 24upx;
      color: #3d3d3d;
    }


  }

  .good_name {
    padding: 10rpx 6rpx;
    font-weight: bold;
    font-size: 28rpx;
    color: #394259;
    line-height: 44rpx;
    text-align: justified;
    font-style: normal;
    text-transform: none;
  }

  .button {
    position: fixed;
    left: 10%;
    bottom: 30rpx;
    width: 80%;
    background-color: #54B9CC;
    color: white;
    font-size: 32rpx;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
  }
</style>
